﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using SlaveComponent;

namespace MasterVNC
{
    public class ControllerSlave
    {
        private frmSlave _Form;
        private Slave _Slave;

        /// <summary>
        /// La form associata al Controller.
        /// </summary>
        public frmSlave Form
        {
            set { _Form = value; }
            get { return _Form; }
        }

        /// <summary>
        /// Inizializza una connessione con il master avente indirizzo ip specificato.
        /// </summary>
        /// <param name="ipAddress">una stringa contenente l'indirizzo ip del master.</param>
        public void StartConnection(string ipAddress){
            Socket socketTcp;

            try
            {
                socketTcp = Slave.ConnectSocket(ipAddress);
            }
            catch (Exception exception)
            {
                _Form.ShowError(exception.Message);
                return;
            }

            NetworkStream stream = new NetworkStream(socketTcp, true);
            _Slave = new Slave(stream);

            try
            {
                _Slave.Status = SlaveState.HANDSHAKING;

                _Slave.ConfigProtocolVersion();
                _Slave.ConfigSecurity();
                _Slave.TestSecurity();
            }
            catch (Exception exception)
            {
                _Form.ShowError(exception.Message + "Closing connection.");
                _Slave.CloseConnection();
                return;
            }
        }

        /// <summary>
        /// Chiude la connessione con il master.
        /// </summary>
        public void CloseConnection()
        {
            _Slave.CloseConnection();
        }
    }
}
